from flask import Blueprint, request, jsonify, current_app
from api.models import BrowseRecord, User
from api import db
from api.errors import bad_request, unauthorized
from api.routes.auth import token_required
from datetime import datetime

browse_bp = Blueprint('browse', __name__)

@browse_bp.route('/api/browse/add', methods=['POST'])
@token_required
def add_browse_record():
    """添加浏览记录"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return bad_request('请提供浏览记录信息')

        required_fields = ['article_id', 'title', 'url']
        if not all(field in data for field in required_fields):
            return bad_request('请提供完整的浏览记录信息')

        # 从请求头获取token
        token = request.headers.get('Authorization')
        if not token:
            return unauthorized('缺少token')
            
        # 根据token获取用户
        user = User.query.filter_by(token=token).first()
        if not user:
            return unauthorized('无效的token')

        # 验证数据
        article_id = data.get('article_id')
        title = data.get('title').strip()
        url = data.get('url').strip()
        cover = data.get('cover', '').strip()

        if not title or len(title) > 255:
            return bad_request('标题长度不符合要求')

        if not url or len(url) > 255:
            return bad_request('URL长度不符合要求')

        if cover and len(cover) > 255:
            return bad_request('封面图URL长度不符合要求')

        # 查找是否已存在该文章的浏览记录
        record = BrowseRecord.query.filter_by(
            user_id=user.id,
            article_id=article_id
        ).first()

        if record:
            # 更新现有记录
            record.title = title
            record.url = url
            record.cover = cover
            record.browse_time = datetime.utcnow()
        else:
            # 创建新记录
            record = BrowseRecord(
                user_id=user.id,
                article_id=article_id,
                title=title,
                url=url,
                cover=cover,
                browse_time=datetime.utcnow()
            )
            db.session.add(record)

        db.session.commit()

        return jsonify({
            'code': 200,
            'message': '添加成功',
            'data': record.to_dict()
        })

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'添加浏览记录失败: {str(e)}')
        return bad_request('添加失败，请稍后重试') 

@browse_bp.route('/api/browse/list', methods=['POST'])
@token_required
def get_browse_records():
    """获取浏览记录列表"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            data = {}

        # 从请求头获取token
        token = request.headers.get('Authorization')
        if not token:
            return unauthorized('缺少token')
            
        # 根据token获取用户
        user = User.query.filter_by(token=token).first()
        if not user:
            return unauthorized('无效的token')

        # 获取分页参数
        page = data.get('page', 1)
        per_page = data.get('per_page', 10)

        # 查询浏览记录
        pagination = BrowseRecord.query.filter_by(
            user_id=user.id
        ).order_by(
            BrowseRecord.browse_time.desc()  # 按浏览时间倒序排序
        ).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )

        # 转换为字典列表
        records = [record.to_dict() for record in pagination.items]

        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'items': records,
                'pagination': {
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'current_page': pagination.page,
                    'per_page': pagination.per_page,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
        })

    except Exception as e:
        current_app.logger.error(f'获取浏览记录失败: {str(e)}')
        return bad_request('获取失败，请稍后重试')


@browse_bp.route('/api/browse/delete', methods=['POST'])
@token_required
def delete_browse_record():
    """删除浏览记录"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data or 'record_ids' not in data:
            return bad_request('请提供要删除的记录ID')

        # 从请求头获取token
        token = request.headers.get('Authorization')
        if not token:
            return unauthorized('缺少token')
            
        # 根据token获取用户
        user = User.query.filter_by(token=token).first()
        if not user:
            return unauthorized('无效的token')

        record_ids = data.get('record_ids')
        if not isinstance(record_ids, list):
            record_ids = [record_ids]

        # 删除记录
        deleted = BrowseRecord.query.filter(
            BrowseRecord.id.in_(record_ids),
            BrowseRecord.user_id == user.id
        ).delete(synchronize_session=False)

        db.session.commit()

        return jsonify({
            'code': 200,
            'message': '删除成功',
            'data': {
                'deleted_count': deleted
            }
        })

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除浏览记录失败: {str(e)}')
        return bad_request('删除失败，请稍后重试') 